package com.ljkj.cordial.lengthtcpheartbeat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class ScreenStateChangeReceive extends BroadcastReceiver {
    private static class InstanceHolder {
        public static ScreenStateChangeReceive INSTANCE = new ScreenStateChangeReceive();
    }

    private ScreenStateChangeObserver mObserver;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
            if (mObserver != null) {
                mObserver.onScreen(false);
            }

        } else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction()) || Intent.ACTION_USER_PRESENT.equals(intent.getAction())) {
            if (mObserver != null) {
                mObserver.onScreen(true);
            }
        }

    }

    /**
     * 表示过滤的是网络改变广播
     *
     * @param context
     */
    public static void registerReceiver(Context context, ScreenStateChangeObserver observer) {
        InstanceHolder.INSTANCE.mObserver = observer;
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);//屏幕关闭，变黑
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);//屏幕开启，变亮
//        intentFilter.addAction(Intent.ACTION_USER_PRESENT);//解锁
        context.registerReceiver(InstanceHolder.INSTANCE, intentFilter);
    }

    public static void unRegisterReceiver(Context context) {
        InstanceHolder.INSTANCE.mObserver = null;
        context.unregisterReceiver(InstanceHolder.INSTANCE);
    }
}
